package com.example.projectmanagement.service;

import com.example.projectmanagement.model.OperationLog;
import com.example.projectmanagement.repository.OperationLogRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import jakarta.persistence.criteria.Predicate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class OperationLogService {
    
    @Autowired
    private OperationLogRepository logRepository;
    
    /**
     * 保存操作日志
     */
    public OperationLog saveLog(OperationLog log) {
        // 确保时间戳被设置
        if (log.getTimestamp() == null) {
            log.setTimestamp(LocalDateTime.now());
        }
        return logRepository.save(log);
    }
    
    /**
     * 根据ID获取日志
     */
    public Optional<OperationLog> getLogById(Long id) {
        return logRepository.findById(id);
    }
    
    /**
     * 获取所有日志（分页）
     */
    public Page<OperationLog> getAllLogs(int page, int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "timestamp"));
        return logRepository.findAll(pageable);
    }
    
    /**
     * 根据条件查询日志（分页）
     */
    public Page<OperationLog> getLogsByCriteria(String username, String operationType, 
                                               LocalDateTime startTime, LocalDateTime endTime, 
                                               int page, int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "timestamp"));
        
        Specification<OperationLog> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            
            if (username != null && !username.isEmpty()) {
                predicates.add(criteriaBuilder.like(root.get("username"), "%" + username + "%"));
            }
            
            if (operationType != null && !operationType.isEmpty()) {
                predicates.add(criteriaBuilder.equal(root.get("operationType"), operationType));
            }
            
            if (startTime != null) {
                predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("timestamp"), startTime));
            }
            
            if (endTime != null) {
                predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("timestamp"), endTime));
            }
            
            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        };
        
        return logRepository.findAll(specification, pageable);
    }
    
    /**
     * 删除所有日志
     */
    public void deleteAllLogs() {
        logRepository.deleteAll();
    }
    
    /**
     * 根据ID删除日志
     */
    public boolean deleteLogById(Long id) {
        if (logRepository.existsById(id)) {
            logRepository.deleteById(id);
            return true;
        }
        return false;
    }
}